package com.brotherly.framework.transaction;

import java.util.Map;

import com.brotherly.framework.service.ServiceHost;
import com.brotherly.framework.timer.TimerListener;
import com.brotherly.framework.timer.TimerService;
import com.brotherly.geo.MapHelper;

public class TimerPacemaker implements Pacemaker, PacemakerFactory, TimerListener
{
    public static final String type = "timer";
    protected ServiceHost host;
    private boolean isOnTask = false;

    protected int stub;

    protected PacemakerWatcher watcher;

    public TimerPacemaker(ServiceHost host)
    {
        this.host = host;
    }

    @Override
    public void active(Transaction transaction, PacemakerWatcher watcher)
    {
        int interval = 1000;

        this.watcher = watcher;

        Map<String, String> props = transaction.getPacemakerProps();
        if (props != null)
        {
            Number value = MapHelper.getNumber(props, "interval");
            if (value.intValue() != 0)
            {
                interval = value.intValue();
            }
        }

        TimerService service = (TimerService) host.getService(TimerService.description);
        stub = service.startTimer(this, interval);
    }

    @Override
    public Pacemaker createInstance()
    {
        return new TimerPacemaker(host);
    }

    @Override
    public void inactive(Transaction transaction)
    {
        TimerService service = (TimerService) host.getService(TimerService.description);
        service.cancel(stub);
    }

    @Override
    public boolean isOnTask()
    {
        return isOnTask;
    }

    @Override
    public void onTimer()
    {
        if (watcher != null)
            watcher.trigger();
    }

    @Override
    public void setOnTask(boolean ontask)
    {
        this.isOnTask = ontask;
    }
}
